<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app" :hoverable="true">
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">电键：{{ data.form.docEntry }}</h3>
            <h3 style="display: inline">名称：{{ data.form.objName }}</h3>
            <h3 style="display: inline">
              状态：
              <a-tag color="#87d068">{{ data.form.docStatus }}</a-tag>
            </h3>
            <h3 style="display: inline">
              审核：
              <a-tag color="#87d068">{{ data.form.approved ? '已审核' : '未审核' }}</a-tag>
            </h3>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()" >返回</a-button>
              <a-button @click="save()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || !data.form.edit)"
                >保存
              </a-button>
              <a-button @click="edit()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || data.form.edit)"
                >编辑
              </a-button>
              <a-button @click="del()" v-if="data.form.docStatus === 'O' && !data.form.approved && !data.form.edit">删除</a-button>
              <a-button @click="approved()" v-if="!data.form.edit">查看审核</a-button>
              <a-dropdown>
                <a-button v-if="!(data.form.edit || data.form.docStatus === 'L')">更多操作</a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" v-if="(data.form.docStatus !== 'C')">关闭单据</a-menu-item>
                    <a-menu-item key="b" v-if="(data.form.docStatus === 'C')">打开单据</a-menu-item>
                    <a-menu-item key="c" v-if="!data.form.approved">发起审核</a-menu-item>
                    <a-menu-item key="d" v-if="data.form.approved">取消审核</a-menu-item>

                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh" value="7"> 刷 新</a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>

      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 4 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="月期间" name="absId">
              <a-input v-if="data.form.edit" v-model:value="data.form.absId" />
              <span v-else>{{ data.form.absId }}</span>
            </a-form-item>
            <a-form-item label="部门" name="deptId">
              <DepartmentTreeSelect v-if="data.form.edit" :init="false" v-model:value="data.form.deptId" @update:value="change" />
              <span v-else>{{ data.form.deptName }}</span>
            </a-form-item>
            <a-form-item label="制单">
              <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="设备名称" name="macName">
              <a-input v-if="data.form.edit" v-model:value="data.form.macName" />
              <span v-else>{{ data.form.macName }}</span>
            </a-form-item>
            <a-form-item label="设备位置" name="macAddress">
              <a-input v-if="data.form.edit" v-model:value="data.form.macAddress" />
              <span v-else>{{ data.form.macAddress }}</span>
            </a-form-item>
            <a-form-item label="费用/H" name="cost">
              <a-input-number style="width: 60%" prefix="￥" v-if="data.form.edit" v-model:value="data.form.cost" :step="0.01" />
              <span v-else>{{ data.form.cost }}￥</span>
            </a-form-item>
            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
              <span v-else>{{ data.form.remark }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="8"></a-col>
        </a-row>
      </a-form>
    </a-card>
  </a-spin>
  <Approvord :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>

  <!---------- 查询表单form end ----------->
</template>
<script setup>
  import { onMounted, reactive, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';

  import { smartSentry } from '/@/lib/smart-sentry';
  import _ from 'lodash';
  import { machineApi } from '/@/api/business/erp/machine-api';
  import { useRouter, useRoute } from 'vue-router';
  import DepartmentTreeSelect from '/@/components/system/department-tree-select/index.vue';
  import { approvordApi } from '/@/api/business/erp/approvord-api.js';

  import Approvord from '/@/components/business/erp/approved.vue';
  import { calendarsApi } from '/@/api/business/erp/calendars-api.js';
  // ---------------------------- 表格列 ----------------------------
  const route = useRoute();
  const router = useRouter();
  const departmentTreeSelect = ref();
  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    categoryId: undefined,
    searchWord: '',
    goodsStatus: undefined,
    place: undefined,
    shelvesFlag: undefined,
    goodsType: undefined,
    pageNum: 1,
    pageSize: 10,
    sortItemList: [],
  };

  // 查询表单form
  const queryForm = reactive(_.cloneDeep(queryFormState));
  const data = reactive({
    form: {
      docEntry: 0,
      objId: '',

      absId: '',
      approved: false,
      docStatus: 'O',

      edit: false,
      lista: [],
    },
    radioGroup: null,
    rules: {
      absId: [{ required: true, message: '请选择月期间' }],
      deptId: [{ required: true, message: '请选择部门' }],
      macName: [{ required: true, message: '请输入设备名称' }],
      macAddress: [{ required: true, message: '请输入设备地址' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    visible: {
      approvord: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
  });
  const tableLoading = ref(false);
  const formRef = ref(null);

  // 初始化
  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
  }

  // 更多操作
  function more({ key }) {
    // 审核处理函数
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      machineApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      machineApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'c') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'A',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'd') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'B',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    }
  }

  // 增删改查
  function add() {
    data.form.objId = 78;
    data.form.objName = '日历';
    data.form.docStatus = 'O';
    data.form.approved = false;
    data.form.absId = null;
    data.form.deptId = null;
    data.form.deptName = null;
    data.form.remark = null;
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/erp/machinea', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          machineApi
            .update(data.form)
            .then((res) => {
              queryData(data.form.docEntry);
              message.success('修改成功！');
            })
            .finally(() => {
              tableLoading.value = false;
            });
        } else {
          machineApi
            .add(data.form)
            .then((res) => {
              data.form.docEntry = res.data;
              message.success('保存成功！');
              router.push({ path: '/erp/machinea', query: { type: 'info', docEntry: res.data } });
              queryData(res.data);
            })
            .finally(() => {
              tableLoading.value = false;
            });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  function edit() {
    data.form.edit = true;
    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        machineApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          router.push({ path: '/erp/machine' });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  function queryData() {
    tableLoading.value = true;
    machineApi
      .info(data.form.docEntry)
      .then((res) => {
        data.form = res.data;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  }

  function refresh() {
    queryData();
  }

  function back() {
    router.push({ path: '/erp/machine' });
  }

  function change(item, key) {
    data.form.deptName = key;
  }

  // 审核------------------------------------------------------------------------------------------------
  function approved() {
    data.approvedData.baseEntry = data.form.docEntry;
    data.approvedData.tabName = data.form.objName;
    data.visible.approvord = true;
  }

  function onclose() {
    data.visible.approvord = false;
    queryData();
  }

  // 行------------------------------------------------------------------------------

  function lineaEdit(key) {
    key.edit = true;
  }

  function lineaAdd() {
    data.form.lista.push({
      docEntry: data.form.docEntry,
      lineNum: data.form.lista.length + 1,
      nowDate: null,
      workDay: false,
      week: '',
      festName: '',
      multiple: 1,
      edit: true,
    });
  }

  function lineaDel(item) {
    data.form.lista.splice(item.lineNum - 1, 1);
    for (let i = item.lineNum - 1; i < data.form.lista.length; i++) {
      data.form.lista[i].lineNum = data.form.lista[i].lineNum - 1;
    }
  }

  onMounted(init);
</script>
